import 'dart:async';
import 'dart:ui' as ui;
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper/components/AlertDialog/circular_progress.dart';
import 'package:wallpaper/components/images/CustomImageCacheManager.dart';
import 'package:wallpaper/components/placeholder/error_eyes.dart';

class ImageViewItem extends StatefulWidget {
  final String smallPath;
  final String largePath;
  final bool isMobile;
  final String tags;
  final Function(double) changeScale;
  final Function(int, int) getSize;
  const ImageViewItem({
    super.key,
    required this.smallPath,
    required this.largePath,
    required this.isMobile,
    required this.tags,
    required this.changeScale,
    required this.getSize,
  });

  @override
  State<ImageViewItem> createState() => _ImageViewState();
}

class _ImageViewState extends State<ImageViewItem> {
  bool isLove = false;
  double iconSize = 30;
  bool isLoading = true;
  Timer? loadTimer;
  bool progress = false;
  final TransformationController _controller = TransformationController();

  // 双击缩放逻辑（放大到 2 倍 / 还原）
  void _handleDoubleTap(TapDownDetails details) {
    final currentScale = _controller.value.getMaxScaleOnAxis();
    final targetScale = currentScale < 2.0 ? 2.0 : 1.0;
    final tapPosition = details.localPosition; // 双击位置
    widget.changeScale(targetScale);

    final targetMatrix = Matrix4.identity()
      ..translate(
        -tapPosition.dx * (targetScale - 1),
        -tapPosition.dy * (targetScale - 1),
      )
      ..scale(targetScale);

    setState(() {
      _controller.value = targetMatrix;
    });
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    loadTimer?.cancel();
    _controller.dispose(); // 修复：添加控制器资源释放
    super.dispose();
  }

  //判断横竖屏并返回对应的 BoxFit
  BoxFit _getImageBoxFit() {
    final screenSize = MediaQuery.of(context).size;
    final isLandscape = screenSize.width > screenSize.height;
    return isLandscape ? BoxFit.fitHeight : BoxFit.fitWidth;
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onDoubleTapDown: _handleDoubleTap,
      child: InteractiveViewer(
        minScale: 1.0,
        maxScale: 3.0,
        transformationController: _controller,
        onInteractionUpdate: (details) {
          widget.changeScale(_controller.value.getMaxScaleOnAxis());
        },
        child: _buildImageView(widget.largePath, _getImageBoxFit()),
      ),
    );
  }

  Widget _buildImageView(String imagePath, BoxFit imageFit) {
    return CachedNetworkImage(
      imageUrl: imagePath,
      fit: imageFit,
      fadeInDuration: const Duration(milliseconds: 200), // 添加淡入效果
      fadeOutDuration: const Duration(milliseconds: 200), // 添加淡出效果
      memCacheWidth: 1080, // 限制内存缓存宽度
      memCacheHeight: 1920, // 限制内存缓存高度
      errorWidget: (context, url, error) => const ErrorEyes(),
      cacheManager: CustomImageCacheManager.instance.cacheManager,
      progressIndicatorBuilder: (context, url, downloadProgress) {
        if (downloadProgress.progress != null || progress) {
          progress = true;
          return Center(
            child: CircularProgress(value: downloadProgress.progress ?? 1),
          );
        } else {
          return const Center(child: CircularProgressIndicator());
        }
      },
      // 图片加载完成后回调
      imageBuilder: (context, imageProvider) {
        // 解析图片获取尺寸
        _getImageSize(imageProvider);

        // 返回最终显示的图片组件
        return Image(
          image: imageProvider,
          fit: imageFit,
          filterQuality: FilterQuality.high, // 提高图片质量
          isAntiAlias: true, // 启用抗锯齿
        );
      },
    );
  }

  // 获取图片宽高的方法（优化解码过程）
  Future<void> _getImageSize(ImageProvider provider) async {
    try {
      // 使用低优先级解码，避免阻塞UI线程
      PaintingBinding.instance.imageCache.maximumSize = 100; // 限制图片缓存大小
      PaintingBinding.instance.imageCache.maximumSizeBytes =
          100 * 1024 * 1024; // 限制为100MB

      // 解析图片数据
      final imageStream = provider.resolve(const ImageConfiguration());
      final completer = Completer<ui.Image>();

      late ImageStreamListener listener;
      listener = ImageStreamListener(
        (ImageInfo info, bool sync) {
          completer.complete(info.image);
          imageStream.removeListener(listener);
        },
        onError: (exception, stackTrace) {
          completer.completeError(exception, stackTrace);
          imageStream.removeListener(listener);
          debugPrint("图片解码错误: $exception");
        },
      );

      imageStream.addListener(listener);

      // 获取图片尺寸
      final ui.Image image = await completer.future;
      final width = image.width;
      final height = image.height;
      widget.getSize(width, height);
    } catch (e) {
      debugPrint("获取图片尺寸失败: $e");
    }
  }
}
